package com.cn.springcloudwechat.controller.pay.notify;

import com.cn.Api.intel.WeChatFeignClient;
import com.cn.springcloudwechat.common.utils.ThreadLocalUtil;
import com.cn.springcloudwechat.common.utils.XMLParser;
import com.cn.springcloudwechat.model.order.YmOrder;
import com.cn.springcloudwechat.service.order.YmOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/web/weixinPayNotify")
public class WeiXinNotifyController {

    @Autowired
    YmOrderService ymOrderService;

    @Autowired
    WeChatFeignClient weChatFeignClient;

    private Logger logger = LoggerFactory.getLogger(WeiXinNotifyController.class);

    /*  @Autowired*/
    @RequestMapping("/mobileNotify")
    public String mobileNotify(HttpServletRequest request, HttpServletResponse response) throws IOException, SAXException, ParserConfigurationException {
        int count = 0;
        InputStream inStream = request.getInputStream();
        System.err.println(inStream);
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String result = new String(outSteam.toByteArray(), "utf-8");//获取微信调用我们notify_url的返回信息
        System.err.println(result+"====================================+++++");
        Map<String, Object> map = null;
        try {
            map = XMLParser.getMapFromXML(result);
            for (String key : map.keySet()) {
                System.out.println(key + "->" + map.get(key));
            }
            if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
                //订单id
                String orderId = map.get("attach").toString();
                System.err.println(orderId+"=========");
                if (!orderId.contains(",")) {
                    YmOrder ymOrder = ymOrderService.getYmOrder(Long.parseLong(orderId));
                    if (ymOrder.getOrderPayState() != null && Integer.valueOf(ymOrder.getOrderPayState()) == 2) {
                        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                    } else {
                        // String orderNo = map.get("trade_no").toString() ;
                        //订单金额
                        Integer totalFee = Integer.valueOf(map.get("total_fee").toString());
                        //应接订单金额
                        //现金支付金额
                        Integer cashFee = Integer.valueOf(map.get("cash_fee").toString());
                        //微信订单号
                        String transactionId = map.get("transaction_id").toString();
                        //商户订单号
                        String outTrade_No = map.get("out_trade_no").toString();
                        //支付完成时间
                        String timeEnd = map.get("time_end").toString();
                        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                        YmOrder ymOrder1 = new YmOrder();
                        ymOrder1.setTotalCost((long) (totalFee));
                        ymOrder1.setOutTradeNo(outTrade_No);
                        ymOrder1.setTransactionId(transactionId);
                        ymOrder1.setOrderId(Long.valueOf(orderId));
                        ymOrder1.setPayTime(format.parse(timeEnd));
                        ymOrder1.setOrderPayState("2");
                        ymOrder1.setOrderPayWay("1");
                        ymOrderService.updateYmOrder(ymOrder1);
                    }
                } else {
                    System.out.println("=====================================" + map.get("result_code").toString());
                    Long id = Long.valueOf(map.get("attach").toString().split(",")[0].toString());
                    System.err.println("订单id");
                    if (weChatFeignClient.getOrder(id)) {
                        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                    } else {
                        weChatFeignClient.payCallback(map);
                    }
                }
                outSteam.close();
                inStream.close();

                }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.getWriter().print("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }

}


